<?php

namespace app\index\controller;

use think\Controller;
use think\Request;
use think\Db;
class RolePermission extends Controller
{
   public function select()
   {
       //
   	$rolePermission = Db::query('select group_concat(permission.name) as pName,group_concat(permission.id) as pid,ur.rname,ur.rid from permission right join 
   	(select roles.name as rname,roles.id as rid,rolepermission.permissionId from roles left join rolepermission on roles.id=rolepermission.roleId ) ur
   	on ur.permissionId=permission.id group by ur.rid');
   	return json($rolePermission);
   }
   
   public function addAndDel()
   {
       //
   	$roleId = input('post.roleId');
   	$needAdds = input('post.needAdd/a');
   	$needDels = input('post.needDel/a');
   	// return json('1'.gettype($needDels));
   	Db::startTrans();
   	try{
   		// $resadd = [];
   		// $resdel = [];
   	foreach($needAdds as $needAdd){
   		$r = Db::execute('insert into rolepermission (id,permissionId,roleId) values (null,?,?)',[$needAdd,$roleId]);
   		// $resadd[] = $needAdd;
   	}
   	foreach($needDels as $needDel){
   		$r = Db::execute('delete from rolepermission where roleId=? and permissionId=?',[$roleId,$needDel]);
   		// $resdel[] = $needDel;
   	}
   	Db::commit();
   	}catch(\Exception $e){
   		Db::rollback();
   		return json('数据回滚');
   	}
   	// $res=["add"=>$needAdd,"del"=>$needDel];
   	// return json($res);
   }
    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        //
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
        //
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        //
    }
}
